from sanic import response
from sanic import Blueprint
import common
import json
from mqtt.tasks import mqtt_publish

mqtt = Blueprint('mqtt_blueprint')

@mqtt.get('/status')
async def env_status(request):
    redis = await common.get_redis()
    status = await redis.get("aihome:status")
    if not status:
        status = {"msg": "no data uploaded"}
    else:
        status = json.loads(status)
    datas = await redis.lrange_aslist("aihome:env:datas", 0, -1)
    if datas:
        datas = [json.loads(x) for x in datas]
    status['datas'] = datas
    return response.json(status)

@mqtt.route('/control')
async def control(request):
    cmd = request.raw_args['cmd']
    if cmd in ['on', 'off']:
        await mqtt_publish("home/heater/cmd", json.dumps({"cmd":cmd})) 
    elif cmd == 'target':
        await mqtt_publish(
            "home/heater/cmd", 
            json.dumps({"cmd":"target", "value": int(request.raw_args['value'])})) 
    return response.redirect('/mqtt/status')
